package com.linln.component.wtpshiro.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.linln.common.exception.jwt.IllegalTokenException;
import com.linln.common.exception.jwt.NoAuthException;
import com.linln.component.wtpshiro.annotation.PassToken;
import com.linln.component.wtpshiro.annotation.UserLoginToken;
import com.linln.common.utils.JwtUtil;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.component.wtpshiro.config
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.component.wtpshiro.config
 * @Description: TODO
 * @date Date : 2020年11月27日 10:53
 */
@Configuration
public class WTPJwtConfig implements WebMvcConfigurer {

    @Autowired
    public UserService userService;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthenticationInterceptor(userService)).addPathPatterns("/**");
    }
}

class AuthenticationInterceptor implements HandlerInterceptor {
    public UserService userService;

    public AuthenticationInterceptor(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new NoAuthException("请登录");
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new IllegalTokenException("非法Token");
                }
                User user = userService.getById(Long.valueOf(userId));
                if (user == null) {
                    throw new NoAuthException("用户不存在，请重新登录");
                }
                if (JwtUtil.verify(token, userId)) {
                    httpServletRequest.setAttribute("token", token);
                    return true;
                } else {
                    throw new NoAuthException("登录信息已失效");
                }

            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
